<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { deleteImageAPI, getImageListAPI } from '@/api'
import errorLogger from '@/utils/errorLogger'
import masonryFun from '@/utils/masonry'
import { Trash } from 'lucide-vue-next'
import { ElMessage } from 'element-plus'

// 分页参数
const pageParams = ref({
  pageNum: 1,
  pageSize: 10,
})

// 获取图片列表
const imageList = ref([])
const total = ref(0)
const fetchImageList = async () => {
  try {
    const response = await getImageListAPI(pageParams.value)
    imageList.value = response.data.images
    total.value = response.data.total
    // 等待 DOM 更新完成再执行布局函数
    await nextTick()

    // 等待图片全部加载完成
    const container = document.querySelector('.image-container')
    const images = container.querySelectorAll('img')

    const allLoaded = Array.from(images).map(
      (img) =>
        new Promise((resolve) => {
          if (img.complete) {
            resolve()
          } else {
            img.onload = () => resolve()
            img.onerror = () => resolve() // 出错也继续
          }
        }),
    )

    await Promise.all(allLoaded)

    // 所有图片加载完后执行布局
    masonryFun()
  } catch (error) {
    errorLogger(error)
  }
}

onMounted(() => {
  fetchImageList()
})

// 删除图片
const handleDelete = async (id) => {
  try {
    await deleteImageAPI(id)
    fetchImageList()
    ElMessage.success('图片删除成功')
  } catch (error) {
    errorLogger(error)
  }
}
</script>

<template>
  <el-card>
    <template #header>
      <el-text size="large">图片管理</el-text>
    </template>

    <!-- 瀑布流布局容器 -->
    <div class="image-container">
      <div v-for="image in imageList" :key="image._id" class="item">
        <img :src="image.url" :alt="image.filename" />
        <div class="operation">
          <el-button circle @click="handleDelete(image._id)"
            ><Trash
          /></el-button>
        </div>
      </div>
    </div>

    <div class="pagination">
      <el-pagination
        v-model:current-page="pageParams.pageNum"
        v-model:page-size="pageParams.pageSize"
        layout="prev, pager, next"
        :total="total"
        @current-change="fetchImageList"
        background />
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.image-container {
  position: relative;

  .item {
    position: absolute;
    width: 300px;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s;

    .operation {
      position: absolute;
      bottom: 0;
      @include flex-center;
      gap: 16px;
      width: 100%;
      height: 40px;
      background: rgba(0, 0, 0, 0.5);
      opacity: 0;
      transition: opacity 0.3s;
    }

    &:hover .operation {
      opacity: 1;
    }

    img {
      width: 100%;
      display: block;
    }
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
